package com.xuecheng.execption;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.validation.UnexpectedTypeException;
import java.util.List;


/**
 * @author 小班哥
 * @version 1.0
 * @date 2023/3/14 15:56
 * @description 全局异常处理器
 */

@Slf4j
@ControllerAdvice//控制器增强
//@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获自定义异常
     * 处理 XueChengPlusException 异常  此类异常是程序员抛出的，可预知异常
     * @param exception
     * @return
     */
    @ResponseBody//把返回的数据封装成JSON
    @ExceptionHandler(XueChengPlusException.class)//捕获哪一种异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//返回状态码 500
    public RestErrorResponse restErrorResponse(XueChengPlusException exception){
        log.debug("捕获自定义异常:{}", exception.getMessage() , exception);
        //拿到异常信息
        String message = exception.getMessage();
        RestErrorResponse restErrorResponse = new RestErrorResponse(message);
        return restErrorResponse;
    }


    /**
     * 捕获系统异常
     * @param exception
     * @return
     */
    @ResponseBody//把返回的数据封装成JSON
    @ExceptionHandler(Exception.class)//捕获哪一种异常
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse SystemException(Exception exception){
        log.debug("捕获系统异常:{}", exception.getMessage() ,exception);
        //拿到异常信息
        if ("不允许访问".equals(exception.getMessage())){
            return new RestErrorResponse("没有操作此功能的权限");
        }
        RestErrorResponse restErrorResponse = new RestErrorResponse(UnifyExceptionMessage.UNKOWN_ERROR.getErrMessage());
        return restErrorResponse;
    }


    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        StringBuffer stringBuffer = new StringBuffer();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        fieldErrors.forEach(error ->{
            stringBuffer.append(error.getDefaultMessage()).append(" ");
        });
        return new RestErrorResponse(stringBuffer.toString());
    }

/*    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse SecurityException(MethodArgumentNotValidException exception){
        if ("不允许访问".equals(exception.getMessage())){
            return new RestErrorResponse("您无权限操作");
        }
    }*/


}
